扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
PHPUnit提供了二个扩展,基于测试类的标准基类PHPUnit2_Framework_TestCase,协助为书写异常和性能回归测试。
7-1 异常
怎么测试异常?当异常抛出时,无法直接使用断言。相反,必须使用PHP 的异常处理机制来书写测试。以下例子示范了入阁测试异常:
<?php
require_once 'PHPUnit2/Framework/TestCase.php';
class ExceptionTest extends PHPUnit2_Framework_TestCase {
public function testException( ) {
try {
// … Code that is expected to raise an
// Exception …
$this->fail('No Exception has been raised.');
}
catch (Exception $expected) {
}
}
}
?>
如果预计要抛出异常的代码没有抛出异常,随后调用的fail()函数(参见本书后的表7)将暂停测试,抛出一个测试有问题的信号。如果预计的异常抛出,每个catch的语句块都会被执行,测试将继续执行。
另外一个测试异常的方法是,测试类可以继承PHPUnit2 _ Extensions_ExceptionTestCase,这可以测试被测试的代码是否抛出了异常。例7展示了如何子类化PHPUnit2_Extensions_ExceptionTestCase 和使用它的setExpectedException() 方法设置预计的异常。如果预计的异常没有抛出,测试将算作是一次失败。
例7.使用PHPUnit2_Extensions_ExceptionTestCase
<?php
require_once 'PHPUnit2/Extensions/ExceptionTestCase.php';
class ExceptionTest extends PHPUnit2_Extensions_
ExceptionTestCase {
public function testException( ) {
$this->setExpectedException('Exception');
}
}
?>
phpunit ExceptionTest
PHPUnit 2.3.0 by Sebastian Bergmann.
F
Time: 0.006798
There was 1 failure:
1) testException(ExceptionTest)
Expected exception Exception
FAILURES!!!
Tests run: 1, Failures: 1, Errors: 0, Incomplete Tests: 0.
表1显示的PHPUnit2_Extensions_ExceptionTestCase 实现的外部协议。
表1 扩展TestCase的外部协议方法
方法 |
描述 |
void setExpectedException(String $exceptionName) |
将$exceptionName变量设置为预计的异常名 |
String getExpectedException( ) |
返回期望的异常名称 |
7-2 性能回归
从PHPUnit2_Extensions _ PerformanceTestCase扩展测试类,可以用于测试函数或方法的调用,如,是否超出的运行时限。
例8展示了怎么继承PHPUnit2_Extensions _ PerformanceTestCase类,使用setMaxRunningTime() 方法设置测试的最大运行时间。如果测试的执行超出了时限,这可以作为测试失败了。
例8 使用PHPUnit2_Extensions_PerformanceTestCase
<?php
require_once 'PHPUnit2/Extensions/PerformanceTestCase.php';
class PerformanceTest extends PHPUnit2_Extensions_
PerformanceTestCase {
public function testPerformance( ) {
$this->setMaxRunningTime(2);
sleep(1);
}
}
?>
Table 2. Performance TestCase external protocols Method
表2 性能测试用例的外部协议方法
表2
方法 |
描述 |
void setMaxRunningTime(integer $maxRunningTime) |
将变量$maxRunningTime(秒)设为测试运行的最大时间。 |
integer getMaxRunningTime( ) |
返回测试允许的最大运行时间 |
查看本文来源
濠电姷顣介埀顒€鍟块埀顒€缍婇幃妯诲緞閹邦剛鐣洪梺闈浥堥弲婊勬叏濠婂牊鍋ㄦい鏍ㄧ〒閹藉啴鏌熼悜鈺傛珚鐎规洘宀稿畷鍫曞煛閸屾粍娈搁梻浣筋嚃閸ㄤ即宕㈤弽顐ュС闁挎稑瀚崰鍡樸亜閵堝懎濮┑鈽嗗亝濠㈡ê螞濡ゅ懏鍋傛繛鍡樻尭鐎氬鏌嶈閸撶喎顕i渚婄矗濞撴埃鍋撻柣娑欐崌閺屾稑鈹戦崨顕呮▊缂備焦顨呴惌鍌炵嵁鎼淬劌鐒垫い鎺戝鐎氬銇勯弽銊ф噥缂佽妫濋弻鐔碱敇瑜嶉悘鑼磼鏉堛劎绠為柡灞芥喘閺佹劙宕熼鐘虫緰闂佽崵濮抽梽宥夊垂閽樺)锝夊礋椤栨稑娈滈梺纭呮硾椤洟鍩€椤掆偓閿曪妇妲愰弮鍫濈闁绘劕寮Δ鍛厸闁割偒鍋勯悘锕傛煕鐎n偆澧紒鍌涘笧閹瑰嫰鎼圭憴鍕靛晥闂備礁鎼€氱兘宕归柆宥呯;鐎广儱顦伴崕宥夋煕閺囥劌澧ù鐘趁湁闁挎繂妫楅埢鏇㈡煃瑜滈崜姘跺蓟閵娧勵偨闁绘劕顕埢鏇㈡倵閿濆倹娅囨い蹇涗憾閺屾洟宕遍鐔奉伓